package com.qfedu.edu.seckill.orderservice.slot.impl;

import com.qfedu.edu.seckill.constance.RedisConstance;
import com.qfedu.edu.seckill.manager.RedisManager;
import com.qfedu.edu.seckill.orderservice.slot.generic.GenericSlot;
import lombok.extern.slf4j.Slf4j;
import org.qfedu.edu.seckill.service.IJwtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author xiaobobo
 * @title: RoutingSlot
 * @projectName cd-java-2404-seckill-parent
 * @description: TODO
 * @date 2025/2/6  9:51
 */
@Component
@Slf4j
public class RoutingSlot extends GenericSlot {

    @Autowired
    private RedisManager redisManager;

    @Autowired
    private IJwtService jwtService;

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 4;
    }

    @Override
    public void dealRequest(HttpServletRequest request, HttpServletResponse response) {
        log.info("RoutingCountInterceptor执行了....");
        //首先获取课程id
        String classId = request.getParameter("classId");
        /**
         * 计数如何来设计呢?
         *    Redis中的String类型
         *    count:sell:课程id  数量
         */
        //首先构建这个key
        String key = RedisConstance.getCountSellPrefix() + classId;
        //递增
        redisManager.incr(key);
        log.info("计数成功....");
        //这里面还需要干一个事情(就是将用户的状态设置为正在购买....)

        //首先组装这个用户购买状态的key
        String userId = getUserId(request);
        //然后组装这个key
        String userSellStatusKey = "sell:status:" + userId + ":" + classId;
        //接下来写入这个正在购买的状态
        redisManager.addString(userSellStatusKey,"buying",30, TimeUnit.DAYS);
    }

    /**
     * 通过request拿到这个用户id
     *
     * @param request
     * @return
     */
    private String getUserId(HttpServletRequest request) {
        String token = request.getHeader("token");
        //然后解析这个token
        return jwtService.getUserId(token);
    }
}
